import { ref } from 'vue'
import { globalStore } from './store/store.global.ts'
import { log } from '@/utils/log.ts'

import { useRoute, type RouteLocationNormalizedLoaded, type Router } from 'vue-router'
import { MlStorage, type MlStorageInterface } from './utils/storage.ts'

/**
 * 全局变量类：用于定义全局变量
 * 1、auto-import插件配置后，可在文件内直接使用_window.xx直接使用变量
 * 2、也可通过import import { _window } from '@/global.ts' 导入
 */
class GlobalVar {
  _env: ImportMetaEnv | any
  _globalStore: any
  _log: any
  localStorage: MlStorageInterface = new MlStorage(localStorage)
  sessionStorage: MlStorageInterface = new MlStorage(sessionStorage)
  isMobile: boolean = false
  private _router: Router | null = null
  private currentRoute = ref<RouteLocationNormalizedLoaded | null>(null)

  dynamicvar: { [key: string]: any } = {} // 代码里动态添加的全局变量

  /**
   * router 等效于 useRouter(), route 等效于 useRoute()
   * 区别：后者(useRoute、useRoute)只能在setup中使用, 前者任意地方可使用
   */
  get router(): Router {
    if (!this._router) {
      throw new Error('Router not initialized. Call init() first.')
    }
    return this._router
  }
  get route(): RouteLocationNormalizedLoaded {
    if (!this.currentRoute.value) {
      // 兜底处理
      this._log.warn('CurrentRoute get error.')
      return useRoute()
    }
    return this.currentRoute.value
  }

  init(router: Router) {
    this._env = import.meta.env
    this._globalStore = globalStore()
    this._log = log
    this._router = router
    this._router.afterEach(to => {
      this.currentRoute.value = to // 保持响应式
    })
  }

  /**
   * 设置全局变量
   * @param key 关键字
   * @param value 内容
   */
  setCustomVar(key: string, value: any) {
    this.dynamicvar[key] = value
  }

  getCustomVar(key: string) {
    if (Object.hasOwn(this.dynamicvar, key)) {
      return this.dynamicvar[key]
    } else {
      this._log.warn(`No set dynamicvar with ${key}`)
      return null
    }
  }
}

export const _window = new GlobalVar()
